package com.itheima.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override//
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        String url=req.getRequestURL().toString();
        log.info("请求的url:{}",url);

        if(url.contains("login")){
            log.info("登录请求，放行");
            return true;
        }

        String token = req.getHeader("token");
        if(!StringUtils.hasLength(token)){
            log.info("token为空，返回未登录的信息");
            Result notLogin = Result.error("NOT_LOGIN");
            String s = JSONObject.toJSONString(notLogin);
            resp.getWriter().write(s);
        }
        try {
            JwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败，返回未登录错误信息");
            Result notLogin = Result.error("NOT_LOGIN");
            String s = JSONObject.toJSONString(notLogin);
            resp.getWriter().write(s);
            return false;
        }
        System.out.println("preHandle..");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
